package com.haier.unpackshell;

import android.content.Context;

import com.haier.commoninterface.ICaculateManagerInterface;
import com.haier.unpackshell.loader.ApkClassLoader;

import java.io.File;
import java.lang.reflect.Method;

public class PluginManager {
    private static PluginManager instance;
    private Context context;

    private PluginManager(Context context) {
        this.context = context;
    }

    public static synchronized PluginManager getInstance(Context context) {
        if (instance == null) {
            instance = new PluginManager(context);
        }
        return instance;
    }

    public Plugin loadPlugin() {
        String pluginPath = context.getCacheDir().getAbsolutePath() + "/" + UnPackShellUtils.UNPACK_SHELL_FILE_NAME;
        Plugin plugin = new Plugin();
        plugin.setPluginPath(pluginPath);

        File file = context.getDir("plugin-opti", Context.MODE_PRIVATE);
        String[] interfaces = new String[]{"com.haier.commoninterface"};
        ApkClassLoader pluginClassLoader = new ApkClassLoader(pluginPath, file.getAbsolutePath(),
                null, context.getClassLoader(), interfaces);
        plugin.setClassLoader(pluginClassLoader);
        return plugin;
    }

    public ICaculateManagerInterface getCaculateManager(Plugin plugin) {
        String sdkClassStr = "com.haier.caculatesdk.CaculateManager";
        String getSdkInstance = "getInstance";

        ICaculateManagerInterface caculateManager = null;
        try {
            Class sdkClass = plugin.getClassLoader().loadClass(sdkClassStr);
            Method sdkGetMethod = sdkClass.getMethod(getSdkInstance);
            caculateManager = (ICaculateManagerInterface) sdkGetMethod.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return caculateManager;
    }

}